package com.yingsheng.bi.hks.basic.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yingsheng.bi.hks.basic.consts.MsgDict;
import com.yingsheng.bi.hks.basic.exception.ServiceRuntimeException;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneId;

@Slf4j
public class JwtUtils {

    public static final Long JWT_EXPIRE = 30 * 24 * 60 * 60L;

    public static final String JWT_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLhHO";

    public static String identity(String channel, String userId) {
        return channel + "@" + userId;
    }

    /**
     * 生成会话Token
     *
     * @param channel 渠道标识
     * @param userId  用户标识
     * @return 会话token
     */
    public static String loginToken(String channel, String userId) {

        String jwtSecret = AppContext.getProperty("jwt-secret", JWT_SECRET);
        Long jwtExpire = AppContext.getProperty("jwt-expire", Long.class, JWT_EXPIRE);
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime expireTime = currentTime.plusSeconds(jwtExpire);

        return JWT.create().withSubject(identity(channel, userId))
                .withIssuedAt(currentTime.atZone(ZoneId.systemDefault()).toInstant())
                .withExpiresAt(expireTime.atZone(ZoneId.systemDefault()).toInstant())
                .sign(Algorithm.HMAC256(jwtSecret));
    }

    /**
     * 校验token的有效性
     *
     * @param token
     * @return
     */
    public static String validate(String token) {
        try {
            String jwtSecret = AppContext.getProperty("jwt-secret", JWT_SECRET);
            Algorithm algorithm = Algorithm.HMAC256(jwtSecret);
            DecodedJWT decodedJWT = JWT.require(algorithm).build().verify(token);
            return decodedJWT.getSubject();
        } catch (JWTVerificationException e) {
            log.error(e.getMessage(), e);
            throw new ServiceRuntimeException(MsgDict.ACCESS_TOKEN_INVALID);
        }
    }



}


